<template>
  <page-layout>
    <!-- 主要区域 -->
    <a-col :span="24">
      <a-card>
        <!-- 列表 -->
        <a-table bordered :columns="bdcolumns" :dataSource="bddata" class="components-table-demo-nested" rowKey="id"
                 ref="tableRef" @expand="expand" >
          <template #bdoperation="{record}">
            <a-button type="primary" size="small" class="editable-add-btn" @click="handleAdd(record.id)">新增</a-button>
          </template>
          <template #expandedRowRender>
            <a-table :columns="innerColumns" :dataSource="innerData" :pagination="false">
              <template v-for="col in ['nianyue', 'byjhtze', 'bywctze', 'ljwctze', 'bzhu']" #[col]="{ text, record }" :key="col">
                <div>
                  <template  v-if="editableData[record.id] && ['nianyue', 'byjhtze', 'bywctze', 'ljwctze', 'bzhu'].includes(col)">
                    <a-input v-model:value="editableData[record.id][col]" style="margin: -5px 0" />
                  </template>
                  <template v-else>
                    {{ text }}
                  </template>
                </div>
              </template>
              <template #operation="{ record }">
                <div style="width: 100px;">
                <span class="editable-row-operations">
                <span v-if="editableData[record.id]">
                  <a @click="baocun(record.id)">保存</a>
                  <a-popconfirm title="确定取消吗？" @confirm="cancel(record.id)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else>
                  <a @click="edit(record.id)">编辑</a>
                </span>
              </span>
                  <a-popconfirm
                    v-if="innerData.length"
                    title="确定删除吗？"
                    @confirm="onDelete(record.id)"
                  >
                    <a>删除</a>
                  </a-popconfirm>
                </div>
              </template>
            </a-table>
          </template>
        </a-table>
      </a-card>
    </a-col>
  </page-layout>
</template>
<script>
import {reactive, ref, toRaw} from 'vue';
import {page, remove, save} from '@/api/module/tzxd_tzwc';
import {cloneDeep} from "lodash-es";
import {message} from "ant-design-vue";
import { v4 as uuidv4 } from "uuid";
import global from '../global/global';

import {page as bdpage} from '@/api/module/sg_biaoduan';

const removeKey = "remove";

export default {
  setup(){
    const editableData = reactive({});

    const bdcolumns = [
      {dataIndex: "biaoduanmingcheng", key: "biaoduanmingcheng", title: "标段名称"},
      {dataIndex: "biaoduanleixing", key: "biaoduanleixing", title: "标段类型"},
      {dataIndex: "zhaobiaoren", key: "zhaobiaoren", title: "招标单位"},
      {dataIndex: "dailijigou", key: "dailijigou", title: "招标代理机构"},
      {dataIndex: "zhaobiaoneirong", key: "zhaobiaoneirong", title: "招标内容"},
      {dataIndex: "zhaobiaowj", key: "zhaobiaowj", title: "招标文件"},
      {dataIndex: "zhongbiaoren", key: "zhongbiaoren", title: "中标单位"},
      {dataIndex: "zhongbiaojia", key: "zhongbiaojia", title: "中标价（万元）"},
      {dataIndex: "hetongqiandingshijian", key: "hetongqiandingshijian", title: "合同签订日期"},
      {dataIndex: "hetongwj", key: "hetongwj", title: "合同（扫描件）"},
      {dataIndex: "zbdwfzr", key: "zbdwfzr", title: "中标单位联系人"},
      {dataIndex: "zbdwfzrphone", key: "zbdwfzrphone", title: "中标单位联系人电话"},
      {key: 'bdoperation', title: '操作', width: 100, slots: {customRender: 'bdoperation'}},
    ]

    ///数据来源
    const bddata = ref([]);
    bdpage({"xiangmuid": global.xmid}).then((response) => {
      bddata.value = response.data.record;
    });

    const innerColumns = [
      {dataIndex: "nianyue", key: "nianyue", title: "年月", slots: {customRender: 'nianyue'}},
      {dataIndex: "byjhtze", key: "byjhtze", title: "本月计划投资额（万元）", slots: {customRender: 'byjhtze'}},
      {dataIndex: "bywctze", key: "bywctze", title: "本月完成投资额（万元）", slots: {customRender: 'bywctze'}},
      {dataIndex: "ljwctze", key: "ljwctze", title: "累计完成投资额（万元）", slots: {customRender: 'ljwctze'}},
      {dataIndex: "bzhu", key: "bzhu", title: "备注", slots: {customRender: 'bzhu'}},
      {key: 'operation', title: '操作', width: 100, slots: {customRender: 'operation'}},
    ];

    const innerData = ref([]);
    const handleAdd = (bdid) => {
      let random = uuidv4().replaceAll("-", "");
      let xmid = global.xmid;
      const addData = {
        id: random,
        xmid: xmid,
        bdid: bdid,
        nianyue: '',
        byjhtze: '',
        bywctze: '',
        ljwctze: '',
        bzhu: '',
      };
      innerData.value.push(addData);
      edit(random);
    };

    const cancel = key => {
      delete editableData[key];
    };

    const onDelete = key => {
      innerData.value = innerData.value.filter(item => item.id !== key);
      remove({"id": key}).then((response) => {
        if(response.success){
          message.success({content: "删除成功", key: removeKey, duration: 1})
        } else {
          message.error({content: "删除失败", key: removeKey, duration: 1})
        }
      })
    };

    const edit = key => {
      editableData[key] = cloneDeep(innerData.value.filter(item => key === item.id)[0]);
    };
    const baocun = key => {
      Object.assign(innerData.value.filter(item => key === item.id)[0], editableData[key]);
      save(toRaw(editableData[key])).then((response) => {
        if(response.success){
          message.success({ content: '提交成功', duration: 1 })
        }else{
          message.error({ content: '提交失败', duration: 1 })
        }
      }).catch(error => {
        console.log('error', error);
      });

      delete editableData[key];
    };

    let expandedRowKeys = []

    const expandedRowsChange = (expandedRows) => {
      expandedRowKeys = expandedRows
      console.log(expandedRowKeys)
    }

    const expand = (expanded, record) => {
      if(expanded){
        page({"xmid": record.xiangmuid, "bdid": record.id}).then((response) => {
          innerData.value = response.data.record;
        });
      }
    }

    return{
      bdcolumns,
      bddata,

      innerColumns,
      innerData,

      expandedRowsChange,
      //expandedRowKeys,

      expand,

      handleAdd,
      onDelete,
      edit,
      baocun,
      editableData,
      cancel,
    }
  }
}
</script>
<style lang="less">
.editable-cell {
  position: relative;
  .editable-cell-input-wrapper,
  .editable-cell-text-wrapper {
    padding-right: 24px;
  }

  .editable-cell-text-wrapper {
    padding: 5px 24px 5px 5px;
  }

  .editable-cell-icon,
  .editable-cell-icon-check {
    position: absolute;
    right: 0;
    width: 20px;
    cursor: pointer;
  }

  .editable-cell-icon {
    margin-top: 4px;
    display: none;
  }

  .editable-cell-icon-check {
    line-height: 28px;
  }

  .editable-cell-icon:hover,
  .editable-cell-icon-check:hover {
    color: #108ee9;
  }

  .editable-add-btn {
    margin-bottom: 8px;
  }
}
.editable-cell:hover .editable-cell-icon {
  display: inline-block;
}
.editable-row-operations a {
  margin-right: 8px;
}
</style>
